package com.xxmw.transaction.common.utils;

import org.apache.commons.compress.utils.CharsetNames;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * AES加密工具
 * @author xiangzuotao
 * @2020年4月20日
 */
public abstract class AESUtil {

	private static final String IV_PARAM = "%Is^X$hU^dmRQAK8";

	private static final String DEFAULT_KEY = "fWV30%FnHxXE0CQV1BPaNBZsDzy#^J^j";

	/**
	 * 加密(使用默认KEY)
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String message) throws Exception {
		return encrypt(message, DEFAULT_KEY);
	}

	/**
	 * 解密(使用默认KEY)
	 * @param message
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String message) throws Exception {
		return decrypt(message, DEFAULT_KEY);
	}


	/**
	 * 加密
	 * @param message
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String message, String key) throws Exception {
		byte[] bs = cipher(message.getBytes(CharsetNames.UTF_8), key.getBytes(CharsetNames.UTF_8), Cipher.ENCRYPT_MODE);
		Base64.Encoder encoder = Base64.getEncoder();
		return encoder.encodeToString(bs);
	}

	/**
	 * 解密
	 * @param message
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String message, String key) throws Exception {
		Base64.Decoder decoder = Base64.getDecoder();
		byte[] content = decoder.decode(message);
		byte[] bs = cipher(content, key.getBytes(CharsetNames.UTF_8), Cipher.DECRYPT_MODE);
		return new String(bs, CharsetNames.UTF_8);
	}

	private static byte[] cipher(byte[] content, byte[] key, int mode) throws Exception {
		 SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
		 IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAM.getBytes(CharsetNames.UTF_8));
		 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		 cipher.init(mode, secretKey, ivParameterSpec);
		 return cipher.doFinal(content);
	}

	public static void main(String[] args) throws Exception {
		System.out.println(encrypt("123456"));
	}
}
